package work.chief.backend.core;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import work.chief.backend.core.builder.DataBuilder;
import work.chief.backend.core.builder.SqlBuilder;
import work.chief.backend.domain.Field;
import work.chief.backend.domain.schame.TableSchema;
import work.chief.backend.domain.vo.GenerateVO;
import work.chief.backend.exception.SchemaException;

import java.util.List;
import java.util.Map;

/**
 * 数据生成接口
 * 测试用
 */
@CrossOrigin
@RestController
@RequestMapping("/")
public class GeneratorController {
    @RequestMapping("generateAll")
    public GenerateVO generateAll(@RequestBody TableSchema tableSchema){
        System.out.println(tableSchema.getFieldList().toString());
        SqlBuilder sqlBuilder = new SqlBuilder();
        String createSql = sqlBuilder.buildCreateTableSql(tableSchema);
        System.out.println(createSql);

        int rowCount = tableSchema.getRowCount();
        List<Map<String, Object>> dataSql = DataBuilder.generateData(tableSchema, rowCount);
        String insertSql = sqlBuilder.buildInsertSql(tableSchema, dataSql);
        System.out.println(insertSql);
        return new GenerateVO();
    }

//    验证表
    public static void validSchema(TableSchema tableSchema) throws Exception {
        if (tableSchema == null) {
            throw new SchemaException("数据为空");
        }
        String tableName = tableSchema.getTableName();
        if (StringUtils.isBlank(tableName)) {
            throw new SchemaException("表名不能为空");
        }
        Integer mockNum = tableSchema.getRowCount();
        // 默认生成 20 条
        if (tableSchema.getRowCount() == null) {
            tableSchema.setRowCount(20);
            mockNum = 20;
        }
        if (mockNum > 100 || mockNum < 10) {
            throw new SchemaException("生成条数设置错误");
        }
        List<Field> fieldList = tableSchema.getFieldList();
        if (CollectionUtils.isEmpty(fieldList)) {
            throw new SchemaException("字段列表不能为空");
        }
        for (Field field : fieldList) {
            validField(field);
        }
    }

//    验证字段
    public static void validField(Field field) throws Exception {
        String fieldName = field.getFieldName();
        String fieldType = field.getFieldType();
        if (StringUtils.isBlank(fieldName)) {
            throw new SchemaException("字段名不能为空");
        }
        if (StringUtils.isBlank(fieldType)) {
            throw new SchemaException("字段类型不能为空");
        }
    }
}
